package wechat

import (
	"context"
	"errors"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type Code2SessionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCode2SessionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Code2SessionLogic {
	return &Code2SessionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *Code2SessionLogic) Code2Session(req *types.Code) (resp *types.Code2SessionRsp, err error) {
	session, err := l.svcCtx.MiniApp.Auth.Session(l.ctx, req.Code)
	if err != nil {
		return nil, err
	}
	if session.ErrCode != 0 {
		return nil, errors.New(session.ErrMsg)
	}

	return &types.Code2SessionRsp{
		SessionKey: session.SessionKey,
		OpenId:     session.OpenID,
	}, nil
}
